#include <string.h>
#include "../../../../mac/mac.h"

mac_init_test()
{
    uint8 extended_slice[8] = {0x00, 0x12, 0x00, 0x34, 0x00, 0x56, 0x00, 0x78};
    uint8 coord_extended_slice[8] = {0x00, 0x12, 0x00, 0x34, 0x00, 0x56, 0x00, 0x78};
    uint64 extended_addr;

    mac_info_init();
    mac_retry_init();
    mac_indir_init();
    buf_init();

    /* set related pib fields */
    mac_set_coord_short_addr(0x8000);
    extended_addr = make_extended_addr(coord_extended_slice);
    mac_set_coord_extended_addr(extended_addr);

    mac_set_short_addr(0x4000);
    extended_addr = make_extended_addr(extended_slice);
    mac_set_extended_addr(extended_addr);

}

int8 poll_req_test(mac_poll_req_t *req)
{
    buf_t *buf;
    uint8 *tx_frm;
    uint8 l;
    mac_hdr_t hdr;
    int8 ret;
    uint8 cmd_id;
    uint16 short_addr;

    if (req == NULL) {
        return MAC_ERR;
    }
    MAC_DEBUG("poll_req_test: 1\n");

    ret = mac_poll_req(req);
    if (ret != MAC_OK) {
        return ret;
    }

    MAC_DEBUG("poll_req_test: 2\n");
    buf = buf_alloc(true);
    if (buf == NULL) {
        return MAC_ERR;
    }

    /* check the frame out, parse and compare it with req */
    tx_frm = get_tx_frm();
    l = get_tx_frm_len();
    MAC_DEBUG("mac_poll_test: length of the generated frame is %d\n", l);
    /* back off the pointer */
    buf->ptr -= (l-1);
    memcpy(buf->ptr, tx_frm, l);

    /* parse the frame */
    mac_parse_hdr(buf, &hdr);
    cmd_id = mac_parse_cmd(buf); 
    MAC_DEBUG("poll_req_poll: cmd_id is %d\n", cmd_id);

    if (cmd_id != CMD_DATA_REQ) {
        buf_free(buf);
        return MAC_ERR;
    }

    short_addr = mac_get_short_addr();
    MAC_DEBUG("poll_req_test: short_addr = 0x%x\n", short_addr);
    MAC_DEBUG("poll_req_test: hdr.src_addr.a.addr16 = 0x%x\n", hdr.src_addr.a.addr16);
    if (short_addr != hdr.src_addr.a.addr16) {
        buf_free(buf);
        return MAC_ERR;
    }

    short_addr = mac_get_coord_short_addr();
    MAC_DEBUG("poll_req_test: coord_short_addr = 0x%x\n", short_addr);
    MAC_DEBUG("poll_req_test: hdr.dest_addr.a.addr64 = 0x%x\n", hdr.dest_addr.a.addr64);
    if (short_addr != hdr.dest_addr.a.addr16) {
        buf_free(buf);
        return MAC_ERR;
    }

    buf_free(buf);
    return MAC_OK;
}

